﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2019/5/5 12:06:50
*说明：<Function>
/**********************************************************************/

using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utilities
{
    /// <summary>
    /// 二维码生成
    /// </summary>
    public class EwmHelper
    {
        //生成带Logo的二维码
        public static void Generate(string content,string logoFile,string outFile)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = qrEncoder.Encode(content);
            
            
            //ModuleSize 设置图片大小  
            //QuietZoneModules 设置周边padding
            /*
                * 5----150*150    padding:5
                * 10----300*300   padding:10
                */
            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(9, QuietZoneModules.Zero), Brushes.Black, Brushes.White);

            DrawingSize dSize = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap map = new Bitmap(315,315);
            Graphics g = Graphics.FromImage(map);
            g.FillRectangle(Brushes.White, 0, 0, 315, 315);
            int x = 315 - dSize.CodeWidth;
            x= x/2;
            render.Draw(g, qrCode.Matrix, new Point(x, x));
            //追加Logo图片 ,注意控制Logo图片大小和二维码大小的比例
            Image img = Image.FromFile(logoFile);

            Point imgPoint = new Point((map.Width - img.Width) / 2, (map.Height - img.Height) / 2);
            g.DrawImage(img, imgPoint.X, imgPoint.Y, img.Width, img.Height);
            map.Save(outFile, ImageFormat.Png);
        }
    }
}
